<template>
  <div>
    <el-row>
      <el-col :span="24">
        <el-form :inline="true">
          <el-form-item>
            <el-button size="small" type="primary" @click="exportBtn()">导出</el-button>
          </el-form-item>
          <el-form-item>
            <el-button size="small" type="primary" @click="dayin2()">打印</el-button>
          </el-form-item>

          <el-form-item>
            <el-radio-group @change="getDataList()" v-model="dataForm.selDateAdd" size="small">
              <el-radio-button label="0">今日</el-radio-button>
              <el-radio-button label="1">昨日</el-radio-button>
              <el-radio-button label="2">本周</el-radio-button>
              <el-radio-button label="3">其他</el-radio-button>
            </el-radio-group>
          </el-form-item>

          <el-form-item v-if="dataForm.selDateAdd == '3'">
            <el-date-picker size="small" @change="getDataList()" v-model="dataForm.startDate" format="yyyy-MM-dd HH:mm:ss"
              type="datetime" placeholder="开始日期" />
            <el-date-picker size="small" @change="getDataList()" v-model="dataForm.endDate" format="yyyy-MM-dd HH:mm:ss"
              type="datetime" placeholder="结束日期" />
          </el-form-item>

          <el-popover placement="top" width="160" v-model="visible">
            <el-checkbox-group v-model="column" @change="columnChange">
              <el-checkbox v-for="(item,index) in selectedColumn" :label="index" :key="index">{{index}}</el-checkbox>
            </el-checkbox-group>

            <el-button slot="reference" size="small" style="margin-top: 2px;float: right;">选择列</el-button>
          </el-popover>
        </el-form>

        <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
          <el-form-item>
            <el-input v-model="dataForm.key" placeholder="关键字" clearable></el-input>
          </el-form-item>

          <el-form-item>
            <el-button @click="getDataList()">查询</el-button>
          </el-form-item>
        </el-form>

        <el-table ref="table" v-loading="dataListLoading" border show-summary :data="dataList" :summary-method="tableSum">

          <el-table-column prop="genera" v-if="selectedColumn['大类']" sortable align="center" label="大类" />
          <el-table-column prop="subclass" v-if="selectedColumn['小类']" sortable align="center" label="小类" />
          <el-table-column prop="shop_number" v-if="selectedColumn['商品编号']" sortable align="center" label="商品编号" />
          <el-table-column prop="shop_name" v-if="selectedColumn['商品名称']" sortable align="center" label="商品名称" />
          <el-table-column prop="type" v-if="selectedColumn['类型']" sortable align="center" label="类型">
            <template slot-scope="{row}">{{ row.type == '1' ? '进货' : row.type == '2' ? '退货' : '' }}</template>
          </el-table-column>
          <el-table-column prop="amount" v-if="selectedColumn['数量']" sortable align="center" label="数量" />
          <el-table-column prop="com_name" v-if="selectedColumn['单位']" align="center" label="单位" />
          <el-table-column prop="create_time" v-if="selectedColumn['操作时间']" sortable align="center" label="操作时间" />
          <el-table-column prop="username" v-if="selectedColumn['操作员']" sortable align="center" label="操作员" />
          <el-table-column prop="remark" v-if="selectedColumn['备注']" align="center" label="备注" />
        </el-table>
      </el-col>
    </el-row>

    <el-pagination
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalPage"
      :page-size="pageSize"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
    />

    <iframe id="print-iframe" style="display: none" />
  </div>
</template>

<script>
import moment from 'moment'

export default {
  data() {
    return {
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,

      dataForm: {
        selDateAdd: '0',
        key: '',

        startDate: '',
        endDate: ''
      },

      column: [
        '商品编号',
        '商品名称',
        '类型',
        '数量',
        '单位',
        '操作时间',
        '操作员',
        '备注'
      ],
      selectedColumn: {
        '大类': false,
        '小类': false,
        '商品编号': true,
        '商品名称': true,
        '类型': true,
        '数量': true,
        '单位': true,
        '操作时间': true,
        '操作员': true,
        '备注': true
      },
      visible: false,
      dataListLoading: false,

      tableHeader: [
        { name: '商品编号', field: 'shop_number' },
        { name: '商品名称', field: 'shop_name' },
        { name: '类型', field: 'type' },
        { name: '数量', field: 'amount' },
        { name: '单位', field: 'nom_name' },
        { name: '操作时间', field: 'create_time' },
        { name: '操作员', field: 'username' },
        { name: '备注', field: 'remark' }
      ]
    }
  },
  created() {
    this.getDataList()
  },
  methods: {
    tableSum(param) {
      const { columns, data } = param
      
      const sums = []
      columns.forEach((column, index) => {
        if (index === 1) {
          sums[index] = "总计"
          return
        }
        if (column.label == '数量') {
          sums[index] = 0
          
          data.forEach(item => {
            sums[index] += item.amount
          })
        }
      })
      return sums
    },

    dayin2() {
      var number = 0 // 列宽
      for (var i = 0; i < this.tableHeader.length; i++) {
        if (this.selectedColumn[this.tableHeader[i].name]) {
          number += 1
        }
      }

      var style = [
        '<style>',
        'body{font-size: 12px; color: #666;}',
        'table{width: 100%; border-collapse: collapse; border-spacing: 0;border-bottom:1px solid #ccc;}',
        'th,td{line-height: 20px; padding: 9px 15px; border: 1px solid #ccc;  text-align: right; font-size: 12px; color: #666;}',
        'a{color: #666; text-decoration:none;}',
        '*.layui-hide{display: none}',
        '</style>'
      ].join('')

      //头部html
      var table = '<table cellspacing="0" cellpadding="0" border="0" class="el-table__header" style="width: 100%;"><thead class="has-gutter"><tr>'
        + `<th style="text-align: center;width: 100%;line-height: 38px;font-size: 20px;font-weight: bold;" colspan="${number}">进退货统计表</th>`
        + '</tr><tr class="">'

      this.tableHeader.forEach((item, index) => {
        if (this.selectedColumn[item.name]) {
          table += `<th colspan="1" rowspan="1" class="el-table_1_column_2 is-center is-leaf"><div class="cell">${item.name}</div></th>`
        }
      })

      table += '</tr></thead><tbody>'

      //身体
      this.dataList.forEach((item, index) => {
        table += '<tr class="">'
        if (this.selectedColumn["商品编号"]) {
          table += '<td rowspan="1" colspan="1" class="el-table_1_column_2 is-center ">' + '<div class="cell">' +
            '<span>' + item.shop_number + '</span></div>' + '</td>'
        }
        if (this.selectedColumn["商品名称"]) {
          table += '<td rowspan="1" colspan="1" class="el-table_1_column_2 is-center ">' + '<div class="cell">' +
            '<span>' + item.shop_name + '</span></div>' + '</td>'
        }
        if (this.selectedColumn["类型"]) {
          table += '<td rowspan="1" colspan="1" class="el-table_1_column_2 is-center ">' + '<div class="cell">' +
            '<span>' + item.type + '</span></div>' + '</td>'
        }
        if (this.selectedColumn["数量"]) {
          table += '<td rowspan="1" colspan="1" class="el-table_1_column_2 is-center ">' + '<div class="cell">' +
            '<span>' + item.amount + '</span></div>' + '</td>'
        }
        if (this.selectedColumn["单位"]) {
          table += '<td rowspan="1" colspan="1" class="el-table_1_column_2 is-center ">' + '<div class="cell">' +
            '<span>' + item.com_name + '</span></div>' + '</td>'
        }
        if (this.selectedColumn["操作时间"]) {
          table += '<td rowspan="1" colspan="1" class="el-table_1_column_2 is-center ">' + '<div class="cell">' +
            '<span>' + item.create_time + '</span></div>' + '</td>'
        }
        if (this.selectedColumn["操作员"]) {
          table += '<td rowspan="1" colspan="1" class="el-table_1_column_2 is-center ">' + '<div class="cell">' +
            '<span>' + item.username + '</span></div>' + '</td>'
        }
        if (this.selectedColumn["备注"]) {
          table += '<td rowspan="1" colspan="1" class="el-table_1_column_2 is-center ">' + '<div class="cell">' +
            '<span>' + item.remark + '</span></div>' + '</td>'
        }
        table += '</tr>'
      })

      var countlist = this.getCountlist(this.dataList)
      for(var i = 0; i < countlist.length; i++){
        table += '<tr class="">'
        if (this.selectedColumn["商品编号"]) {
          table += '<td rowspan="1" colspan="1" class="el-table_1_column_2 is-center ">' + '<div class="cell">' +
              '<span>' + countlist[i].name + '总计</span></div>' + '</td>'
        }
        if (this.selectedColumn["商品名称"]) {
          table += '<td rowspan="1" colspan="1" class="el-table_1_column_2 is-center ">' + '<div class="cell">' +
            '<span>' + "" + '</span></div>' + '</td>'
        }
        if (this.selectedColumn["类型"]) {
          table += '<td rowspan="1" colspan="1" class="el-table_1_column_2 is-center ">' + '<div class="cell">' +
            '<span>' + "" + '</span></div>' + '</td>'
        }
        if (this.selectedColumn["数量"]) {
          table += '<td rowspan="1" colspan="1" class="el-table_1_column_2 is-center ">' + '<div class="cell">' +
            '<span>' + countlist[i].count + '</span></div>' + '</td>'
        }
        if (this.selectedColumn["单位"]) {
          table += '<td rowspan="1" colspan="1" class="el-table_1_column_2 is-center ">' + '<div class="cell">' +
            '<span>' + "" + '</span></div>' + '</td>'
        }
        if (this.selectedColumn["操作时间"]) {
          table += '<td rowspan="1" colspan="1" class="el-table_1_column_2 is-center ">' + '<div class="cell">' +
            '<span>' + "" + '</span></div>' + '</td>'
        }
        if (this.selectedColumn["操作员"]) {
          table += '<td rowspan="1" colspan="1" class="el-table_1_column_2 is-center ">' + '<div class="cell">' +
            '<span>' + "" + '</span></div>' + '</td>'
        }
        if (this.selectedColumn["备注"]) {
          table += '<td rowspan="1" colspan="1" class="el-table_1_column_2 is-center ">' + '<div class="cell">' +
            '<span>' + "" + '</span></div>' + '</td>'
        }
        table += '</tr>'
      }

      table += '</tbody></table>'
      table += '<div style="width: 100%; text-align: right;">'
        + `<span style="margin-right: 20px;">打印时间：${this.moment(new Date())}</span>`
        + `<span>打印人：${this.$store.state.user.name}</span>`
        + '</div>'

      var iframe = document.getElementById('print-iframe')
      var doc = null
      document.body.appendChild(iframe)
      doc = iframe.contentWindow.document
      doc.write(style + table)
      doc.close()
      iframe.contentWindow.focus()
      iframe.contentWindow.print()
      if (navigator.userAgent.indexOf('MSIE') > 0) {
        document.body.removeChild(iframe)
      }
    },


    getDataList() {
      if (this.dataForm.startDate != null && this.dataForm.startDate != "") {
        if (this.dataForm.startDate instanceof Date) {
          this.dataForm.startDate = this.gettime(this.dataForm.startDate)
        }
      }
      if (this.dataForm.endDate != null && this.dataForm.endDate != "") {
        if (this.dataForm.endDate instanceof Date) {
          this.dataForm.endDate = this.gettime(this.dataForm.endDate);
        }
      }

      this.$http({
        url: this.$http.adornUrl('/hotel/thotelfloorroomconsumeshoppurchasale/purchasale'),
        method: 'get',
        params: this.$http.adornParams({
          page: this.pageIndex,
          limit: this.pageSize,
          ...this.dataForm
        })
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.dataList = data.purchaSale.list
          this.dataList.forEach(item => {
            if (item.type == '2') {
              item.amount *= -1
            }
          })

          this.totalPage = data.purchaSale.total
        } else {
          this.dataList = []
          this.totalPage = 0
        }
        this.dataListLoading = false
      })
    },
    getCountlist(arrList) {
      const names = [...new Set(arrList.map(item => item.shop_number))]

      let countlist = []
      for (var i = 0; i <= names.length; i++) {
        if (names[i]) {
          countlist[i] = { name: names[i], count: 0 }
        } else {
          countlist[names.length] = { name: '', count: 0 }
        }
      }

      for (var i = 0; i < countlist.length - 1; i++) {
        arrList.forEach(item => {
          if (item.shop_number == countlist[i].name) {
            countlist[i].count += item.amount
            countlist[countlist.length - 1].count += item.amount
          }
        })
      }
      return countlist
    },

    sizeChangeHandle(val) {
      this.pageIndex = 1
      this.pageSize = val
      this.getDataList()
    },
    currentChangeHandle(val) {
      this.pageIndex = val
      this.getDataList()
    },

    columnChange() {
      Object.keys(this.selectedColumn).forEach(item => {
        this.selectedColumn[item] = false
      })

      this.column.forEach(item => {
        this.selectedColumn[item] = true
      })
    },
    exportBtn() {
      window.open(this.$http.adornUrl('/hotel/thotelfloorroomconsumeshoppurchasale/purchasale_export'))
    },

    // ->
    moment(date) {
      return moment(date).format('YYYY-MM-DD')
    },
    gettime(time) {
      var year = time.getFullYear()
      var month = time.getMonth() + 1
      var day = time.getDate()
      var h = time.getHours()
      var s = time.getMinutes()
      var mm = time.getSeconds()

      if (month < 10) { month = "0" + month }
      if (day < 10) { day = "0" + day }
      if (h < 10) { h = "0" + h }
      if (s < 10) { s = "0" + s }
      if (mm < 10) { mm = "0" + mm }

      return year + "-" + month + "-" + day + "  " + h + ":" + s + ":" + mm
    }
  }
}
</script>
